//
//  LRXAddrcInfoController.m
//  路人侠
//
//  Created by zhangxulong on 2/9/16.
//  Copyright © 2016 zhangxulong. All rights reserved.
//

#import "LRXAddrcInfoController.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import "LRXAddrCell.h"
#import "LRXMapSearchCache.h"
#import "LRXBase64Encode.h"

#import "LRXMapCellModel.h"
#import "LRXRegularExpression.h"
@interface LRXAddrcInfoController()<
    UITableViewDataSource,
    UITableViewDelegate,
    AMapSearchDelegate,
    UITextFieldDelegate
>

@property (nonatomic,weak) UITextField * addrText;
@property (nonatomic,strong) UIDynamicAnimator * animator;
@property (nonatomic,strong) AMapSearchAPI * search;
@property (nonatomic,strong) NSMutableArray * resultAddrs;
@property (nonatomic,copy) NSString * mapSearchAddr;
@property (nonatomic,weak) UIImageView * locationBac;
@property (nonatomic,weak) UITableView * tableView;
@property (nonatomic,strong) NSMutableArray * bedroomModel;
@property (nonatomic,weak) LRXBedroom * bedroom;


@end
@implementation LRXAddrcInfoController
- (NSMutableArray *)resultAddrs
{
    if (_resultAddrs == nil) {
        _resultAddrs = [NSMutableArray array];
    }
    return _resultAddrs;
}
- (AMapSearchAPI *)search
{
    if (_search == nil) {
        _search = [[AMapSearchAPI alloc]init];
    }
    return _search;
}
- (UIDynamicAnimator *)animator
{
    if (_animator == nil) {
        _animator = [[UIDynamicAnimator alloc]initWithReferenceView:self.view];
    }
    return _animator;
}

- (void)viewDidLoad
{
//    NSArray * p = @[@"3",@"三",@"东软",@"三期",@"3期",@"东软3期",@"三期宿舍",@"3期宿舍",@"三期7",@"3期宿舍7",@"三期宿舍7"
//                    ,@"东软三",@"东软3期大魔王",@"3期东软",@"7",@"7A",@"大连东软",@"东软信息学院",@"东你",@"东期",@"东东",@"软东",@"东",@"东软期",@"三期7A",@"大连东软信息学院三期宿舍楼7A403",@"大连东软信息学院三期",@"大"];
//    for (NSString * str in p) {
//        NSLog(@"%@ -- %d",str ,[LRXRegularExpression regularExpression:str withPattern:@"((大连)?东软((信息)?(学院|三期))?|([三3]期?(宿舍)?)\\d?){1,}[^期]*|\\d{1,2}\\w?"]);
//    }
    
    self.view.backgroundColor = [UIColor whiteColor];
    // 布局导航栏的控件
    self.navigationItem.title = self.NavTitle;
    
    //加载数据
    [self loadbedRoomData];
    
    //布局头部视图
    [self layoutHeardView];
    
    //地点内容的布局
    [self layoutContentView];
    
    
    if (self.locationAddr.length > 0 && ![self.locationAddr isEqualToString:@"送达地点"] && ![self.locationAddr isEqualToString:@"购买地点"]) {
        self.addrText.text = self.locationAddr;
    }
}

- (void)loadbedRoomData
{
    NSString * schoolPath = [[NSBundle mainBundle] pathForResource:@"n_d_i" ofType:nil];
    NSString * content = [NSString stringWithContentsOfFile:schoolPath encoding:NSUTF8StringEncoding error:nil];
    NSArray * bedroom = [NSJSONSerialization JSONObjectWithData:[[LRXBase64Encode base64Decode:content] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
    NSMutableArray * bedroomModel = [NSMutableArray array];
    for (NSDictionary * dic in bedroom) {
        LRXBedroom * bedroom = [LRXBedroom bedroomWithDic:dic];
        [bedroomModel addObject:bedroom];
    }
    self.bedroomModel = bedroomModel;
    
}

//头部布局和背景的设置
- (void)layoutHeardView
{
    CGFloat addrTextY = 188 * hScale;
    CGFloat addTextH = 75 * hScale;
    
    
    //定位的背景照片
    CGFloat locationBacH = addrTextY + addTextH + 23 * hScale;
    UIImageView * locationBac = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"location_bk"]];
    locationBac.frame = CGRectMake(0, 0, MainScreenW, locationBacH);
    self.locationBac = locationBac;
    [self.view addSubview:locationBac];
    
    
    
    UITextField * addrText = [[UITextField alloc]init];
    addrText.clearButtonMode = UITextFieldViewModeWhileEditing;
    addrText.backgroundColor = [UIColor colorWithRed:255 green:255 blue:255 alpha:0.5];
    addrText.frame = CGRectMake(38 * wScale, addrTextY , 563 * wScale, addTextH);
    addrText.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10*wScale, 0)];
    addrText.leftViewMode = UITextFieldViewModeAlways;
    addrText.layer.cornerRadius = 6 * hScale;
    addrText.font = [UIFont systemFontOfSize:25 * hScale];
    
    //改变addrText的return按键
    addrText.returnKeyType = UIReturnKeySearch;
    addrText.delegate = self;
    
    
   
    
    [self.view addSubview:addrText];
    [addrText addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.addrText = addrText;
    
    //如果定位到了 就自动搜索一下
}

//布局内容视图
- (void)layoutContentView
{
    CGFloat tableViewY = CGRectGetMaxY(self.locationBac.frame);
    
    UITableView * tableView = [[UITableView alloc]init];
    
    tableView.backgroundColor = [UIColor colorWithRed:244 green:244 blue:244];
    
    tableView.frame = CGRectMake(0, tableViewY, MainScreenW, MainScreenH - tableViewY - statuesH - NavbarH);
    tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.rowHeight = 110 * hScale;
    self.tableView = tableView;
    
    
    [self.view addSubview:tableView];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * ADDRREUESD = @"ADDRREUESD";
    LRXAddrCell * cell = [tableView dequeueReusableCellWithIdentifier:ADDRREUESD];
    if (cell == nil) {
        cell = [[LRXAddrCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ADDRREUESD];
    }
    if (self.resultAddrs.count) {
        [cell addrLayout:self.resultAddrs[indexPath.row]];
    }
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.resultAddrs.count;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * addrText;
    LRXBedroom * bedModel = nil;
    if (self.resultAddrs.count &&  self.resultAddrs[indexPath.row] != nil && [[self.resultAddrs[indexPath.row] mapName] length]) {
        addrText = [NSString stringWithFormat:@"%@",[self.resultAddrs[indexPath.row] mapName]];
        bedModel = [self.resultAddrs[indexPath.row] bedroom];
    }

    //UITextField 的更新
    self.addrText.text = addrText;
    //地点的更新
    self.locationAddr = addrText;
    self.bedroom = bedModel;
    [self popViewController];
}


//每当文字改变时，调用 搜索函数
- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField.text.length > 0) {
        [self mapSeachAddrFromLocation:textField.text];
    }
    else
    {
        [self.resultAddrs removeAllObjects];
        [self.tableView reloadData];
    }
    
}

/**
 *  从本地文件（模型）搜索数据
 *
 *  @param mapSearchAddr 搜索的地址
 */
- (void)mapSeachAddrFromLocation:(NSString *)mapSearchAddr
{
    
    [self.resultAddrs removeAllObjects];

        
    if([LRXRegularExpression regularExpression:mapSearchAddr withPattern:@"(大连)?东软((信息)?(学院)?)?"])
    {
        for (LRXBedroom * bedroom in self.bedroomModel) {
            NSString * name = [NSString stringWithFormat:@"大连东软三期%@楼",bedroom.blockNum];
            NSDictionary * dic = @{@"district":@"大连东软信息学院三期",@"name":name,@"bedroom":bedroom};
            LRXMapCellModel * cellModel = [LRXMapCellModel mapCellModelWithDic:dic];
            [self.resultAddrs addObject:cellModel];
        }
        [self mapSeach:@"大连东软信息学院"];
    }
    if([LRXRegularExpression regularExpression:mapSearchAddr withPattern:@".*(([三3]期?(宿舍)?)\\d?){1,}[^期]*"])
    {
        for (LRXBedroom * bedroom in self.bedroomModel) {
            NSString * name = [NSString stringWithFormat:@"大连东软三期%@楼",bedroom.blockNum];
            NSDictionary * dic = @{@"district":@"大连东软信息学院三期",@"name":name,@"bedroom":bedroom};
            LRXMapCellModel * cellModel = [LRXMapCellModel mapCellModelWithDic:dic];
            [self.resultAddrs addObject:cellModel];
        }
        [self mapSeach:@"大连东软信息学院三期"];
    }
    if([LRXRegularExpression regularExpression:mapSearchAddr withPattern:@".*\\d{1,2}\\w?"])
    {
        for (LRXBedroom * bedroom in self.bedroomModel) {
            if ([bedroom.blockNum containsString:mapSearchAddr]) {
                
                NSString * name = [NSString stringWithFormat:@"大连东软三期%@楼",bedroom.blockNum];
                NSDictionary * dic = @{@"district":@"大连东软信息学院三期",@"name":name,@"bedroom":bedroom};
                LRXMapCellModel * cellModel = [LRXMapCellModel mapCellModelWithDic:dic];
                [self.resultAddrs addObject:cellModel];
            }
        }
    }
    else{
        [self mapSeach:mapSearchAddr];
    }


    if(self.resultAddrs.count == 0) return;
   
    [self.tableView reloadData];

}


//从高德数据库 搜索 文字
- (void)mapSeach:(NSString * )mapSearchAddr
{
    [AMapSearchServices sharedServices].apiKey = MKKey;
    
    //初始化检索对象
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    
    //构造AMapInputTipsSearchRequest对象，设置请求参数
    AMapInputTipsSearchRequest *tipsRequest = [[AMapInputTipsSearchRequest alloc] init];
    tipsRequest.keywords = mapSearchAddr;
    tipsRequest.city = @"大连";
    tipsRequest.cityLimit = YES;
    
    //发起输入提示搜索
    [self.search AMapInputTipsSearch: tipsRequest];
    
}
//实现输入提示的高德数据库回调函数
-(void)onInputTipsSearchDone:(AMapInputTipsSearchRequest *)request response:(AMapInputTipsSearchResponse *)response
{
    //移除数组中所有的东西
    if(response.tips.count == 0) return;
    //通过AMapInputTipsSearchResponse对象处理搜索结果
    for (AMapTip * regeocode in response.tips) {
        if (regeocode.district && regeocode.name) {
        
            NSDictionary * dic = @{@"district":regeocode.district,@"name":regeocode.name,@"bedroom":[NSNull null]};
            LRXMapCellModel * cellModel = [LRXMapCellModel mapCellModelWithDic:dic];
            [self.resultAddrs insertObject:cellModel atIndex:0];
        }
    }
    [self.tableView reloadData];

}

//返回界面 地点的更新（我要求带界面）
- (void)popViewController
{
    //代理方法回调 更改按钮的text
    if ([self.updateAddrTextDelegate respondsToSelector:@selector(upAddrText:btnFlag:withBedRoom:)]) {
        
        if (self.addrText.text.length == 0) {
            if (self.btnFlag == SENDADDRBTNFLAG || self.btnFlag == SENDADDRASSFLAG) {
                self.addrText.text = @"送达地点";
            }
            if (self.btnFlag == BUYADDRBTNFLAG || self.btnFlag == BUYADDRASSFLAG) {
                self.addrText.text = @"购买地点";
            }
            if (self.btnFlag == STARTADDRBTNFLAG) {
                self.addrText.text = @"起始地";
            }
            if (self.btnFlag == ENDADDRBTNFLAG) {
                self.addrText.text = @"目的地";
            }
        }
    
        [self.updateAddrTextDelegate upAddrText:self.addrText.text btnFlag:self.btnFlag withBedRoom:self.bedroom];
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}
@end
